package com.totoro.rabbitmq.PTP;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.totoro.rabbitmq.RabbitMQUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 一个发送者多个接收者 发送方。为了消息的不丢失，我们将queue设置为durible，所以此时queue的独占性exclusive应该设为false
 * 因为
 * Created by Niki on 2018/3/29 7:49
 */
public class PTPMoreService {
    private static String queue_name = "hello_demo2_queue";
    private static String msg = "Hello Rabbit!";

    private static void sendMsg(){
        ConnectionFactory connectionFactory = RabbitMQUtil.getConnectionFactory();
        Connection connection = null;
        Channel channel = null;

        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();

            //声明队列
            channel.queueDeclare(queue_name, true, false, false, null);

            /* 发送消息
                RabbitMQ默认采用direct类型的Exchange。因为Service 将消息发送到Exchange，由Exchange根据规则路由到相应的Queue
                客户端则从Queue中读取消息。这里采用了默认的Exchange，默认采用queue的名称作为routingKey。
             */
            channel.basicPublish("", queue_name, null, msg.getBytes());

        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            RabbitMQUtil.closeChannel(channel);
            RabbitMQUtil.closeConnection(connection);

        }
    }
}
